<?php

namespace app\common\service\sim;

use app\common\service\service;
use app\util\Tools;

class OpenSim extends service
{
    protected $saltKey;
    protected $common;
    protected $base_url;

    public $url;
    public $method;
    public $params;

    public function __construct()
    {
        parent::__construct();
        $this->curl->setHeader('Content-Type', 'application/json');

        $this->base_url = env('sim.base_url');
        $this->saltKey = env('sim.salt_key');

        $this->common['apiId'] = env('sim.api_id');
        $this->common['channelCode'] = env('sim.channel_code');
    }

    public function request()
    {
        $this->params['sign'] = $this->makeSign();
        $request_method = strtoupper($this->method);
        // $this->curl->$request_method($this->url);
        //https://yktcs.cmccsim.com
        if ($request_method == 'POST') {
            // 调用移动超级SIM卡数据库信息
            // 自动获取SIM卡SEID信息
            $this->post($this->url, true);
        } else {
            $this->get($this->url);
        }
        return $this->payload();
    }

    public function makeSign()
    {
        $str = '';
        $args = $this->sortKey();
        foreach ($args as $key => $arg) {
            $str .= $key.'='.$this->sortString($arg);
        }
        return md5($str.$this->saltKey);
    }

    public function getParams()
    {
        return $this->params;
    }

    public function setParams($params)
    {
        $this->params = array_merge($this->common, $params);
        $this->params['reqTime'] = date('YmdHis').Tools::get_millisecond();
        return $this;
    }

    public function setMethod($method)
    {
        $this->method = $method;
        return $this;
    }
    public function setUrl($url)
    {
        $this->url = $this->base_url.$url;
        return $this;
    }

    private function sortString($str)
    {
        if (is_array($str)) {
            $str = json_encode($str, JSON_UNESCAPED_UNICODE);
        }
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        asort($arr);
        return implode('',$arr);
    }
}